package com.mj.haier.calc.servlet;

import java.io.IOException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StopWatch;

/**
 * 责任链
 */
public class ApplicationFilterChain implements FilterChain {


    private final Logger log = LoggerFactory.getLogger(ApplicationFilterChain.class);
    // 当前执行filter的offset
    private int offset = 0;
    // 当前filter的总长度
    private int n;
    private Filter[] filters;
    private Servlet servlet;

    public ApplicationFilterChain(Filter[] filters, Servlet servlet){
        this.filters = filters;
        this.servlet = servlet;
        this.n = filters.length;
    }

    @Override
    public void doFilter(Request req, Response res) throws IOException, ServletException {
        if(offset < n){
            log.debug("当前过滤器组Filters的位置: {}", offset);
            Filter filter = filters[offset++];
            log.debug("获取当前第 {} 个过滤器对象 {}", offset, filter.getClass().getName());
            filter.doFilter(req, res, this);
        }else{
            servlet.servlet(req, res);
            offset = 0;
        }
    }
}
